package com.sans.common.util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;


import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import java.net.URLEncoder;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@SuppressWarnings("restriction")
public class RSA {
	private static PrivateKey privateKey;
	/** 指定加密算法为RSA */
	private static String ALGORITHM = "RSA";
	
	private static String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCfRTdcPIH10gT9f31rQuIInLwe"  
            + "\r" + "7fl2dtEJ93gTmjE9c2H+kLVENWgECiJVQ5sonQNfwToMKdO0b3Olf4pgBKeLThra" + "\r"  
            + "z/L3nYJYlbqjHC3jTjUnZc0luumpXGsox62+PuSGBlfb8zJO6hix4GV/vhyQVCpG" + "\r"  
            + "9aYqgE7zyTRZYX9byQIDAQAB" + "\r";
	private static final String PASSWORD_CRYPT_KEY = "D6D2402F1C98E208FF2E863AA29334BD65AE1932A821502D9E5673CDE3C713ACFE53E2103CD40ED6BEBB101B484CAE83D537806C6CB611AEE86ED2CA8C97BBE95CF8476066D419E8E833376B850172107844D394016715B2E47E0A6EECB3E83A361FA75FA44693F90D38C6F62029FCD8EA395ED868F9D718293E9C0E63194E87";


	private static String PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJ9FN1w8gfXSBP1/"
			+ "\r"
			+ "fWtC4gicvB7t+XZ20Qn3eBOaMT1zYf6QtUQ1aAQKIlVDmyidA1/BOgwp07Rvc6V/"
			+ "\r"
			+ "imAEp4tOGtrP8vedgliVuqMcLeNONSdlzSW66alcayjHrb4+5IYGV9vzMk7qGLHg"
			+ "\r"
			+ "ZX++HJBUKkb1piqATvPJNFlhf1vJAgMBAAECgYA736xhG0oL3EkN9yhx8zG/5RP/"
			+ "\r"
			+ "WJzoQOByq7pTPCr4m/Ch30qVerJAmoKvpPumN+h1zdEBk5PHiAJkm96sG/PTndEf"
			+ "\r"
			+ "kZrAJ2hwSBqptcABYk6ED70gRTQ1S53tyQXIOSjRBcugY/21qeswS3nMyq3xDEPK"
			+ "\r"
			+ "XpdyKPeaTyuK86AEkQJBAM1M7p1lfzEKjNw17SDMLnca/8pBcA0EEcyvtaQpRvaL"
			+ "\r"
			+ "n61eQQnnPdpvHamkRBcOvgCAkfwa1uboru0QdXii/gUCQQDGmkP+KJPX9JVCrbRt"
			+ "\r"
			+ "7wKyIemyNM+J6y1ZBZ2bVCf9jacCQaSkIWnIR1S9UM+1CFE30So2CA0CfCDmQy+y"
			+ "\r"
			+ "7A31AkB8cGFB7j+GTkrLP7SX6KtRboAU7E0q1oijdO24r3xf/Imw4Cy0AAIx4KAu"
			+ "\r"
			+ "L29GOp1YWJYkJXCVTfyZnRxXHxSxAkEAvO0zkSv4uI8rDmtAIPQllF8+eRBT/deD"
			+ "\r"
			+ "JBR7ga/k+wctwK/Bd4Fxp9xzeETP0l8/I+IOTagK+Dos8d8oGQUFoQJBAI4Nwpfo"
			+ "\r"
			+ "MFaLJXGY9ok45wXrcqkJgM+SN6i8hQeujXESVHYatAIL/1DgLi+u46EFD69fw0w+"
			+ "\r" + "c7o0HLlMsYPAzJw=" + "\r";
	private static BouncyCastleProvider bouncyCastleProvider = new BouncyCastleProvider();
	static {
		try {
			privateKey = loadPrivateKey(PRIVATE_KEY);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	 /** 
     * 从字符串中加载公钥 
     *  
     * @param publicKeyStr 
     *            公钥数据字符串 
     * @throws Exception 
     *             加载公钥时产生的异常 
     */  
    public static PublicKey loadPublicKey(String publicKeyStr) throws Exception  
    {  
        try  
        {  
            byte[] buffer = RSABase64Utils.decode(publicKeyStr);  
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);  
            return (RSAPublicKey) keyFactory.generatePublic(keySpec);  
        } catch (NoSuchAlgorithmException e)  
        {  
            throw new Exception("无此算法");  
        } catch (InvalidKeySpecException e)  
        {  
            throw new Exception("公钥非法");  
        } catch (NullPointerException e)  
        {  
            throw new Exception("公钥数据为空");  
        }  
    }  
	
	 /**
     * 加密方法
     *
     * @return
     */
	public static String encrypt(String source) throws Exception {
		Key key = loadPublicKey(PUBLIC_KEY);
		/** 得到Cipher对象来实现对源数据的RSA加密 */
		Cipher cipher = Cipher.getInstance(ALGORITHM,bouncyCastleProvider);
		cipher.init(Cipher.ENCRYPT_MODE, key);
		byte[] b = source.getBytes();
		/** 执行加密操作 */
		byte[] b1 = cipher.doFinal(b);
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(b1).replaceAll("\\r|\\n", "");
	}
    
    
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		/*try {
			String i = encrypt("18715019002");
			System.out.println(URLEncoder.encode(i));
			System.out.println(">>>>>>>>>>>>>>>>>"+RSAJieMi(i));
			System.out.println(IOS3DESUtil.encryptThreeDESECB("18756968631", PASSWORD_CRYPT_KEY));
//			System.out.println(">>>>>>>>>>>>>>"+RSAJieMi("a1VTnh64HioKT1sqE8/PXBYkb8wiDr6PQmb6Nqc2I9yBNJDvwN/x3IjWb5nNRi/lz1sQrS0lSpo6iso+kUGphS7Jq3KbeRNXv6DVEoGclQIwuMOVq5kI8zt/QzX3wbYb8aPKsrWcbDGwAZI+z18lRGPAOa45i4PrpxZjvypfNkI="));
		} catch (Exception e) {
			e.printStackTrace();
		}*/
		String date = "20230301100352";
		System.out.println(getMinutesDiff(date));

	}

	private static boolean getMinutesDiff(String date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		Date nowDate = new Date();
		Date start = null;
		try {
			start = sdf.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		long time = nowDate.getTime() - (start != null ? start.getTime() : 0);
		return time <= 60 * 1000 * 10;
	}

	/**
	 * RSA 解密密码
	 * 
	 * @return 密码
	 */
	public static String RSAJieMi(String pwd) {
		String decryptStr = null;
		try {
			// 私钥
			// 因为RSA加密后的内容经Base64再加密转换了一下，所以先Base64解密回来再给RSA解密
			byte[] decryptByte = decryptData(RSABase64Utils.decode(pwd),
					privateKey);
			decryptStr = new String(decryptByte);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return decryptStr;
	}

	/**
	 * 用私钥解密 RSA用
	 * 
	 * @param encryptedData
	 *            经过encryptedData()加密返回的byte数据
	 * @param privateKey
	 *            私钥
	 * @return
	 */
	private static byte[] decryptData(byte[] encryptedData, PrivateKey privateKey) {
		try {
			Cipher clipher = Cipher.getInstance("RSA", bouncyCastleProvider);
			clipher.init(Cipher.DECRYPT_MODE, privateKey);
			return clipher.doFinal(encryptedData);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 从字符串中加载私钥<br>
	 * RSA用 加载时使用的是PKCS8EncodedKeySpec（PKCS#8编码的Key指令）。
	 * 
	 * @param privateKeyStr
	 * @return
	 * @throws Exception
	 */
	private static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception {
		try {
			byte[] buffer = RSABase64Utils.decode(privateKeyStr);
			PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("无此算法");
		} catch (InvalidKeySpecException e) {
			throw new Exception("私钥非法");
		} catch (NullPointerException e) {
			throw new Exception("私钥数据为空");
		}
	}
}
